package cms.simmytech.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.PostConstruct;

import cms.simmytech.response.BaseResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class UploadUtil {

	@Value("${simmytech.savePath}")
	private String savePath;

	@Value("${simmytech.savePath.bi}")
	private String savePathBi;

	@Value("${simmytech.reqPath}")
	private String reqPath;

	@Value("${simmytech.reqPath.bi}")
	private String reqPathBi;

	@Value("${simmytech.filepath}")
	private String filePath;

	@Value("${simmytech.document.type}")
	private String dType;



	public String getdType() {
		return dType;
	}

	public void setdType(String dType) {
		this.dType = dType;
	}

	public String getiType() {
		return iType;
	}

	public void setiType(String iType) {
		this.iType = iType;
	}

	public String getvType() {
		return vType;
	}

	public void setvType(String vType) {
		this.vType = vType;
	}

	@Value("${simmytech.image.type}")
	private String iType;

	@Value("${simmytech.video.type}")
	private String vType;

	private  String documentType;

	private  String imageType;

	private  String videoType;



	private final static byte DOCUMENT_TYPE = 1;

	private final static byte IMAGE_TYPE = 2;

	private final static byte VIDEO_TYPE = 3;


	private static Map<Byte, Set<String>> FILE_INFO_MAP = new HashMap<Byte, Set<String>>();

	@PostConstruct
	public void init() {
		setConfigInfo(this);
		getInstance();
	}

	public void setConfigInfo(UploadUtil uploadUtil) {
		documentType = uploadUtil.getdType();
		imageType = uploadUtil.getiType();
		videoType = uploadUtil.getvType();

	}

	private Set<String> getTypeSet(String typeString) {
		if (StringUtils.isEmpty(typeString)) {
			return null;
		}
		String[] types = typeString.split(",");
		Set<String> set = new HashSet<>(types.length);
		for (String string : types) {
			set.add(string);
		}
		return set;

	}

	public void getInstance() {
		// 文档类型
		Set<String> dSet = getTypeSet(documentType);
		if (null != dSet && dSet.size() > 0) {
			FILE_INFO_MAP.put(DOCUMENT_TYPE, dSet);
		}

		// 图片类型
		Set<String> iSet = getTypeSet(imageType);
		if (null != iSet && iSet.size() > 0) {
			FILE_INFO_MAP.put(IMAGE_TYPE, iSet);
		}

		// 视频类型
		Set<String> vSet = getTypeSet(videoType);
		if (null != vSet && vSet.size() > 0) {
			FILE_INFO_MAP.put(VIDEO_TYPE, vSet);
		} // 此静态方法供外部直接访问


	}

	public String uploadFile(MultipartFile file) {
		String fullReqPath = "";
		try {
			byte[] bytes = file.getBytes();
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
			String fileNewName = UUID.randomUUID().toString() + "." + suffix;
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
			String time = sf.format(new Date());
			String saveFullPath = savePath + time;
			File pathDir = new File(saveFullPath);
			ImageUtils.toListImage(pathDir, saveFullPath);
			if (!pathDir.exists()) {
				pathDir.mkdir();
			}
			Path path = Paths.get(saveFullPath + "/" + fileNewName);
			Files.write(path, bytes);
			fullReqPath = reqPath + time + "/" + fileNewName;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return fullReqPath;
	}

	public BaseResponse uploadFile(MultipartFile file, byte type) {
		BaseResponse response = new BaseResponse(ResultCode.SERVER_ERROR);
		try {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
			if (!FILE_INFO_MAP.get(type).contains(suffix)) {
				response.setResponse(ResultCode.INVALID_PARAMETER);
				return response;
			}
			byte[] bytes = file.getBytes();
			String fileNewName = UUID.randomUUID().toString() + "." + suffix;
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
			String time = sf.format(new Date());
			String saveFullPath = savePath + time;
			File pathDir = new File(saveFullPath);
			if (!pathDir.exists()) {
				pathDir.mkdir();
			}
			Path path = Paths.get(saveFullPath + "/" + fileNewName);
			Files.write(path, bytes);
			SFTPUtil sftpUtil=new SFTPUtil("root","Amazon2020!@#Resource1223$%^1235","ec2-52-81-200-205.cn-north-1.compute.amazonaws.com.cn",22);
			sftpUtil.login();
			sftpUtil.upload(saveFullPath,path.toString());
			sftpUtil.logout();
//			if (type==2)
//				ImageUtils.toListImage(new File(saveFullPath + "/" + fileNewName),saveFullPath+"/list");
			response.setStat(ResultCode.SUCCESS);
			response.setMess(reqPath + time + "/" + fileNewName);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
	public BaseResponse uploadFile(MultipartFile file, byte type,String savePostion) {
		BaseResponse response = new BaseResponse(ResultCode.SERVER_ERROR);
		try {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
			if (!FILE_INFO_MAP.get(type).contains(suffix)) {
				response.setResponse(ResultCode.INVALID_PARAMETER);
				return response;
			}
			byte[] bytes = file.getBytes();
			String fileNewName = UUID.randomUUID().toString() + "." + suffix;
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
			String time = sf.format(new Date());
			String saveFullPath = savePathBi + time;
			File pathDir = new File(saveFullPath);
			if (!pathDir.exists()) {
				pathDir.mkdirs();
			}
			Path path = Paths.get(saveFullPath + "/" + fileNewName);
			Files.write(path, bytes);
			SFTPUtil sftpUtil=new SFTPUtil("root","Amazon2020!@#Resource1223$%^1235","ec2-52-81-200-205.cn-north-1.compute.amazonaws.com.cn",22);
			sftpUtil.login();
			sftpUtil.upload(saveFullPath,path.toString());
			sftpUtil.logout();
//			if (type==2)
//				ImageUtils.toListImage(new File(saveFullPath + "/" + fileNewName),saveFullPath+"/list");
			response.setStat(ResultCode.SUCCESS);
			response.setMess(reqPathBi + time + "/" + fileNewName);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	public String uploadFile(MultipartFile file, String root) {

		String fullReqPath = "";
		root = (root != null && !root.equals("") ? root : "");
		try {
			byte[] bytes = file.getBytes();
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
			String fileNewName = UUID.randomUUID().toString() + "." + suffix;
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
			String time = sf.format(new Date());
			String saveFullPath = savePath + root + time;
			File pathDir = new File(saveFullPath);
			if (!pathDir.exists() || !pathDir.isDirectory()) {
				pathDir.mkdir();
			}
			Path path = Paths.get(saveFullPath + "/" + fileNewName);
			Files.write(path, bytes);
			fullReqPath = reqPath + root + time + "/" + fileNewName;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return fullReqPath;

	}

	/**
	 * 获取网络图片
	 * 
	 * @param imagePath
	 * @throws Exception
	 */
	public File getHttpImage(String imagePath) throws Exception {
		// new一个URL对象
		URL url = new URL(imagePath);
		// 打开链接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置请求方式为"GET"
		conn.setRequestMethod("GET");
		// 超时响应时间为5秒
		conn.setConnectTimeout(5 * 1000);
		// 通过输入流获取图片数据
		InputStream inStream = conn.getInputStream();
		// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
		byte[] data = readInputStream(inStream);
		// new一个文件对象用来保存图片，默认保存当前工程根目录
		File imageFile = new File(savePath + "/" + imagePath.substring(imagePath.lastIndexOf("/"), imagePath.length()));
		// 创建输出流
		FileOutputStream outStream = new FileOutputStream(imageFile);
		// 写入数据
		outStream.write(data);
		// 关闭输出流
		outStream.close();
		return imageFile;
	}

	public byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		// 创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		// 每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		// 使用一个输入流从buffer里把数据读取出来
		while ((len = inStream.read(buffer)) != -1) {
			// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		// 关闭输入流
		inStream.close();
		// 把outStream里的数据写入内存
		return outStream.toByteArray();
	}
}
